<template>
  <div id="patch">
    <ReturnPage />
    <div class="mt20">
      <el-form
        size="mini"
        :inline="true"
        :model="query"
        class="demo-form-inline"
        ref="query"
      >
        <el-form-item label="补丁库名称:">
          <el-input
            v-model="query.name"
            placeholder="请输入补丁库名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="ml10" @click="getList()"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="warning" class="ml10" @click="reset('query')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        size="mini"
        @click="
          dialogVisible = true;
          btnLoading = false;
        "
        >新增</el-button
      >
      <el-button type="warning" size="mini" @click="distribute(_, 1)"
        >批量分发</el-button
      >
      <!-- 分发记录列表 -->
      <div class="tp_box mt20">
        <el-table
          height="calc(100vh - 330px)"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="name" label="补丁库名称"></el-table-column>
          <el-table-column
            prop="version"
            label="版本号"
            show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="fileCount"
            label="包含文件数量"
            style="text-aligin-center"
          >
          </el-table-column>
          <el-table-column prop="fileNames" label="包含文件名称">
          </el-table-column>

          <el-table-column
            prop="fileSize"
            label="文件大小(M)"
            show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{
              (scope.row.fileSize / 1048576).toFixed(2) == "0.00"
                ? "0.01"
                : (scope.row.fileSize / 1048576).toFixed(2)
            }}</template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="描述"
            show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="dispenseStatus"
            label="分发状态"
            show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <el-tag
                size="mini"
                type="success"
                v-if="scope.row.dispenseStatus == 1"
              >
                {{ scope.row.dispenseStatus | filterdispenseStatus }}
              </el-tag>
              <el-tag
                size="mini"
                type="danger"
                v-if="scope.row.dispenseStatus != 1"
              >
                {{ scope.row.dispenseStatus | filterdispenseStatus }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作" width="210">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="warning"
                @click="distribute(scope.row, 0)"
                >分发</el-button
              >
              <el-button size="mini" type="danger" @click="del(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="tableData.length > 0"
          :total="this.total"
          :page.sync="query.pageNum"
          :limit.sync="query.pageSize"
          @pagination="getList"
        />
      </div>
      <!--新增表单-->
      <el-dialog
        :title="'新增补丁库'"
        :visible.sync="dialogVisible"
        @close="closeDialog('ruleForm')"
      >
        <el-form
          ref="ruleForm"
          :rules="rules"
          label-width="150px"
          :model="ruleForm"
        >
          <el-form-item label="补丁库名称" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入补丁库名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="ruleForm.version"
              placeholder="请输入版本号"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="ruleForm.description"
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传文件">
            <el-upload
              class="upload-demo"
              style="text-align: left"
              ref="upload"
              name="files"
              :action="upload.url"
              :headers="upload.headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess"
              :file-list="fileList"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleChange"
              :data="{
                name: ruleForm.name,
                version: ruleForm.version,
                description: ruleForm.description,
                hostId: ruleForm.hostId,
              }"
            >
              <el-button
                slot="trigger"
                size="small"
                icon="el-icon-plus"
              ></el-button>
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
            <!-- 文件列表 -->
            <el-table :data="fileList" style="width: 100%" size="mini">
              <el-table-column prop="name" label="文件名称"> </el-table-column>
              <el-table-column prop="size" label="文件大小">
                <template slot-scope="scope">{{
                  scope.row.size | filterSize
                }}</template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="delFile(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              :loading="btnLoading"
              @click="submitFileForm('ruleForm')"
              >提交</el-button
            >
            <el-button @click="cancellation('ruleForm')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--编辑表单-->
      <el-dialog :title="'编辑补丁库'" :visible.sync="editdialogVisible">
        <el-form
          ref="editruleform"
          :rules="rules"
          label-width="150px"
          :model="editruleform"
        >
          <el-form-item label="补丁库名称" prop="name">
            <el-input
              v-model="editruleform.name"
              placeholder="请输入补丁库名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="editruleform.version"
              placeholder="请输入版本号"
            ></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="editruleform.description"
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传文件">
            <el-upload
              class="upload-demo"
              style="text-align: left"
              ref="upload"
              name="files"
              :action="upload.url"
              :headers="upload.headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess"
              :file-list="fileUrlList"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleChange"
              :data="{
                name: editruleform.name,
                version: editruleform.version,
                description: editruleform.description,
                hostId: editruleform.hostId,
                id: editruleform.id,
              }"
            >
              <el-button
                slot="trigger"
                size="small"
                icon="el-icon-plus"
              ></el-button>
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
            <!-- 文件列表 -->
            <el-table :data="editfileList" style="width: 100%" size="mini">
              <el-table-column prop="name" label="文件名称"> </el-table-column>
              <el-table-column prop="size" label="文件大小">
                <template slot-scope="scope">{{
                  scope.row.size | filterSize
                }}</template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="delFile(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="editsubmitFileForm('editruleform')"
              :loading="btnLoading"
              >提交</el-button
            >
            <el-button @click="editcancellation('editruleform')"
              >取消</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--分发补丁文件-->
      <el-dialog
        :title="'分发补丁文件'"
        :visible.sync="distributedialogVisible"
      >
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="远程主机IP" prop="hostIp">
            <el-input
              v-model="form.hostIp"
              placeholder="请输入远程主机IP"
            ></el-input>
          </el-form-item>
          <el-form-item label="分发目录" prop="remoteFileDir">
            <el-input
              v-model="form.remoteFileDir"
              placeholder="请输入分发目录"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="密码"
              show-password
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="distributeBt('form')"
              >提交</el-button
            >
            <el-button @click="cancellationdialogVisible('ruleForm')"
              >取消</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
//接口
import {
  getPatchList_Api, //列表
  delPatch_Api, //删除
  dispensePatch_Api, //分发
  getinfoPatch_Api, //查询
} from "@/api/automated/host.js";

export default {
  data() {
    return {
      //提交按钮loading
      btnLoading: false,
      //上传文件参数
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/automated/patchlibrary",
      },
      //文件上传
      fileList: [],
      editfileList: [],
      //添加应用程序表单
      ruleForm: {
        name: null,
        version: null,
        description: null,
        hostId: null,
        files: null,
      },
      editruleform: {
        name: null,
        version: null,
        description: null,
        hostId: null,
        files: null,
        fileNames: null,
        fileSize: null,
      },
      form: {
        hostIp: null,
        remoteFileDir: null,
        username: null,
        password: null,
        dataId: null,
      },
      rules: {
        name: [
          { required: true, message: "请输入补丁库名称", trigger: "blur" },
        ],
        version: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        description: [
          { required: true, message: "请输入描述", trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },

      // },
      //文件上传
      fileList: [],
      //表单
      fileUrlList: [],
      //补丁或应用程序
      title: "",
      //分页
      query: {
        pageNum: 1,
        pageSize: 10,
        name: "",
      },
      total: 0,
      //列表数据
      tableData: [],
      dialogVisible: false, //新增弹框
      editdialogVisible: false, //编辑
      distributedialogVisible: false, //分发弹框
      multipleSelection: [], //多选
      singleOrMultiple: false, //true单个分发false多个分发
    };
  },
  methods: {
    //分发的弹窗
    distribute(row, type) {
      //1 批量  0 单个
      this.distributedialogVisible = true;

      if (type == 1) {
        //批量
        this.singleOrMultiple = false;
      } else {
        //单个
        this.form.dataId = row.id.toString();
        this.singleOrMultiple = true;
      }
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //分发
    distributeBt(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //判断是批量还是单个分发
          if (this.singleOrMultiple) {
            //单个
            dispensePatch_Api(this.form).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.getList();
                this.distributedialogVisible = false;
              } else {
                this.$$message.success("操作失败");
              }
            });
          } else {
            //批量 使用promise.all
            if (this.multipleSelection.length) {
              const itemIds = this.multipleSelection.map((item) =>
                item.id.toString()
              );
              const tempArr = itemIds.map((item) => {
                return dispensePatch_Api({ ...this.form, dataId: item });
              });
              Promise.all(tempArr)
                .then((res) => {
                  this.$message.success(res[0].msg);
                  this.getList();
                  this.distributedialogVisible = false;
                })
                .catch((error) => {
                  this.$message.error("操作失败");
                });
            }
          }
        } else {
          console.log("error submit!!");
          this.btnLoading = false;
          return false;
        }
      });
    },
    // 提交上传文件
    submitFileForm(formName) {
      this.btnLoading = true;
      //验证表单是否输入正确
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 创建新的数据对象
          let formData = new FormData();
          // 将上传的文件放到数据对象中
          const fileName = [];
          if (this.fileList.length == 0) {
            console.log(this.fileList);
            this.$message.info("请至少选择一个文件");
            return;
          }
          this.fileList.forEach((file) => {
            formData.append("files", file.raw);
            fileName.push(file.name);
          });
          // console.log(fileName)
          var nary = fileName.sort();

          for (var i = 0; i < fileName.length; i++) {
            if (nary[i] == nary[i + 1]) {
              return this.$message.error("禁止上传相同的文件!");
            }
          }
          // 应用程序名
          formData.append("name", this.ruleForm.name);
          formData.append("version", this.ruleForm.version);
          formData.append("description", this.ruleForm.description);
          formData.append("hostId", this.ruleForm.hostId);
          // 自定义上传
          this.uploadFile(formData)
            .then((response) => {
              this.btnLoading = false;
              this.$message.success("上传成功！");
              this.getList();
              this.dialogVisible = false;
            })
            .catch((error) => {
              this.$message.error("上传失败！");
              this.btnLoading = false;
            });
        } else {
          console.log("error submit!!");
          this.btnLoading = false;
          return false;
        }
      });
    },
    //文件上传
    handleFileSuccess(response, file, fileList) {
      if (this.dialogVisible) {
        this.resetForm("ruleForm");
        this.dialogVisible = false;
      } else if (this.editdialogVisible) {
        this.resetForm("editruleform");
        this.editdialogVisible = false;
      }
      this.$refs.upload.clearFiles();
      this.$message.success("操作成功");
      this.dialogVisible = false;
      this.getList();
    },
    // delFile (row) {
    //     this.fileList.splice(
    //         this.fileList.findIndex((item) => item.uid == row.uid),
    //         1
    //     );
    // },
    //编辑表单
    edit(row) {
      this.editfileList = [];
      getinfoPatch_Api(row.id).then((res) => {
        this.editruleform = { ...res.data };
        let fileNames;
        if (res.data.fileNames) {
          fileNames = res.data.fileNames.split(",");
        }
        res.data.fileUrlList.forEach((item, index) => {
          this.editfileList.push({
            name: fileNames[index],
            size: res.data.fileSize,
            id: index,
          });
        });

        this.editdialogVisible = true;

        this.btnLoading = false;
      });
    },
    //编辑
    editsubmitFileForm(formName) {
      this.btnLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 创建新的数据对象
          let formData = new FormData();
          // 将上传的文件放到数据对象中
          const fileName = [];
          this.fileList.forEach((file) => {
            formData.append("files", file.raw);
            fileName.push(file.name);
          });

          // 应用程序名
          formData.append("name", this.editruleform.name);
          formData.append("version", this.editruleform.version);
          formData.append("description", this.editruleform.description);
          formData.append("hostId", this.editruleform.hostId);
          formData.append("id", this.editruleform.id);
          this.editfileList.forEach((item, index) => {
            formData.append("fileNameList", item.name);
          });
          // 自定义上传
          this.uploadEdit_File(formData)
            .then((response) => {
              if (response.data.code == 200) {
                this.btnLoading = false;
                this.$message.success(response.data.msg);
                this.editdialogVisible = false;
                this.getList();
                this.fileList = [];
                this.editfileList = [];
              } else {
                this.$message.error(response.data.msg);
                this.editdialogVisible = false;
              }
            })
            .catch((error) => {
              this.btnLoading = false;
              this.$message.error("操作失败！");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //编辑表单取消
    editcancellation() {
      this.editdialogVisible = false;
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.fileList = [];
    },
    //关闭表单
    cancellation() {
      this.dialogVisible = false;
    },

    cancellationdialogVisible() {
      this.distributedialogVisible = false;
    },
    //获取列表数据
    getList() {
      this.query.hostid = this.$route.query.hostid;
      getPatchList_Api(this.query).then((res) => {
        if (res) {
          this.tableData = res.rows;
          this.total = res.total;
        }
      });
    },
    //关闭新增弹窗
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.fileList = [];
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleChange(file, fileList) {
      this.btnLoading = false;
      this.fileList = fileList;
      if (this.editdialogVisible) {
        //追加进表格
        this.editfileList.push(file);
      }
    },
    //删除文件
    delFile(row) {
      if (row.uid) {
        //删本地上传的
        this.fileList.splice(
          this.fileList.findIndex((item) => item.uid == row.uid),
          1
        );
        //删除表格展示的
        this.editfileList.splice(
          this.fileList.findIndex((item) => item.uid == row.uid),
          1
        );
      } else {
        //删接口返回的
        this.editfileList.splice(
          this.editfileList.findIndex((item) => item.id == row.id),
          1
        );
      }
    },
    //删除
    del(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          delPatch_Api(id)
            .then((res) => {
              this.getList();
              this.$message.success("删除成功");
            })
            .catch((error) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    uploadFile(params) {
      return axios.post(
        process.env.VUE_APP_BASE_API + `/automated/patchlibrary`,
        params,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: "Bearer " + getToken(),
          },
        }
      );
    },
    // 封装的编辑上传请求
    uploadEdit_File(params) {
      return axios.put(
        process.env.VUE_APP_BASE_API + `/automated/patchlibrary`,
        params,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: "Bearer " + getToken(),
          },
        }
      );
    },
  },
  filters: {
    filterSize(val) {
      const units = ["Bytes", "KB", "MB", "GB", "TB"];
      let index = 0;
      let size = val;
      // 将文件大小逐步除以1024，直到达到最适合的单位

      if (size >= 1024) {
        while (size >= 1024 && index < units.length - 1) {
          size /= 1024;
          index++;
        }
        return size.toFixed(2) + " " + units[index];
      } else {
        return size + " " + "Bytes";
      }
      // 保留两位小数
    },
    filterdispenseStatus(val) {
      switch (val) {
        case 1:
          return "成功";
        case 0:
          return "失败";
        case 2:
          return "失败";
      }
    },
  },
  created() {
    this.query.hostId = this.$route.query.hostid;
    this.ruleForm.hostId = this.$route.query.hostid; //主机id
    this.getList();
    this.title = this.$route.query.name;
  },
};
</script>

<style lang="scss" scoped>
.el-form-item {
  text-align: right;
}
</style>

